package cn.com.greatwall.generator.service.impl;

import java.io.File;

import org.springframework.stereotype.Service;

import cn.com.greatwall.common.utils.StringUtils;
import cn.com.greatwall.generator.domain.GenConfig;
import cn.com.greatwall.generator.repository.GenConfigRepository;
import cn.com.greatwall.generator.service.GenConfigService;
import lombok.RequiredArgsConstructor;

/**
 * @Author herw
 * @Time 2020-11-07 20:18:36
 * @Version 1.0
 * @Description: TODO(用一句话描述该文件做什么)
 */
@Service
@RequiredArgsConstructor
public class GenConfigServiceImpl implements GenConfigService {
    private final GenConfigRepository genConfigRepository;

    @Override
    public GenConfig find(String tableName) {
        GenConfig genConfig = genConfigRepository.findByTableName(tableName);
        if (genConfig == null) {
            return new GenConfig(tableName);
        }
        return genConfig;
    }

    @Override
    public GenConfig update(String tableName, GenConfig genConfig) {
        String separator = File.separator;
        String[] paths;
        String symbol = "\\";
        if (symbol.equals(separator)) {
            paths = genConfig.getPath().split("\\\\");
        } else {
            paths = genConfig.getPath().split(File.separator);
        }
        StringBuilder api = new StringBuilder();
        for (String path : paths) {
            api.append(path);
            api.append(separator);
            if ("src".equals(path)) {
                api.append("api");
                break;
            }
        }
        genConfig.setApiPath(api.toString());
        return genConfigRepository.save(genConfig);
    }
}
